package org.springblade.core.opc;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue;
import org.springblade.core.etl.service.EtlJob;
import org.springblade.core.opc.config.OpcConfig;
import org.springblade.core.tool.utils.FnKit;

import java.util.*;

/**
 * 数据相关操作
 */
@Slf4j
public class OpcDao {

    /**
     * 读取opc
     *
     * @param opcConfig 命名空间
     * @param keyList
     * @param etl       默认服务
     * @return
     * @throws Exception
     */
    public static Map<String, Object> readOpcValue(OpcConfig opcConfig, List<String> keyList, EtlJob etl) throws Exception {
        if (keyList == null || keyList.size() == 0) {
            log.debug("keyList is null");
            return Collections.emptyMap();
        }
        if (FnKit.isEmpty(opcConfig.getNamespaceIndex()) || FnKit.isEmpty(opcConfig.getUrl())) {
            log.debug("namespaceIndex / url is null");
            return Collections.emptyMap();
        }
        OpcUaClient client;
        try {
            client = OpcClientPool.getClient(opcConfig, etl);
        } catch (Exception ex) {
//            log.debug(ex.getMessage(),ex);
            log.error("创建PLC的OPC客户端失败，原因：" + ex.getMessage());
            return Collections.emptyMap();
        }
        List<DataValue> dataValues;
        try {
            dataValues = OpcUaUtil.readValues(opcConfig.getNamespaceIndex(), keyList, client);
        } catch (Exception ex) {
            log.debug(ex.getMessage(), ex);
            throw ex;
        }
        Map<String, Object> dataMap = new HashMap<>();
        if (dataValues == null || dataValues.size() == 0) {
            return dataMap;
        }
        String key;
        DataValue dv;
        for (int i = 0; i < keyList.size(); i++) {
            key = keyList.get(i);
            dv = dataValues.get(i);
            if (Objects.nonNull(dv) && Objects.nonNull(dv.getValue()) && Objects.nonNull(dv.getValue().getValue())) {
                dataMap.put(key, dv.getValue().getValue());
                log.debug("读取 key:{} ,value:{}", key, dataMap.get(key));
            }
        }
        return dataMap;
    }

}
